<template>
  <div class="follow-plan">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <!-- 随访周期 -->
      <el-form-item label="随访周期" prop="plansPeriodId">
        <el-select
          v-model="formData.plansPeriodId"
          placeholder="请选择随访周期"
          style="width: 100%"
          :disabled="isViewMode"
        >
          <el-option
            v-for="item in followUpPlanCondition"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <!-- 开始日期 -->
      <el-form-item label="开始日期" prop="startDate">
        <el-date-picker
          v-model="formData.startDate"
          type="date"
          placeholder="选择开始日期"
          style="width: 100%"
          value-format="x"
          :disabled="isViewMode"
        />
      </el-form-item>

      <!-- 结束日期 -->
      <el-form-item label="结束日期" prop="endDate">
        <el-date-picker
          v-model="formData.endDate"
          type="date"
          placeholder="选择结束日期"
          style="width: 100%"
          value-format="x"
          :disabled="isViewMode"
        />
      </el-form-item>

      <!-- 随访时间 -->
      <el-form-item label="随访时间" prop="executionTime">
        <el-time-picker
          v-model="timeValue"
          is-range
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="HH:mm"
          style="width: 100%"
          :disabled="isViewMode"
          @change="handleTimeChange"
        />
      </el-form-item>

      <!-- 备注 -->
      <el-form-item label="备注" prop="notes">
        <el-input
          v-model="formData.notes"
          type="textarea"
          :rows="4"
          placeholder="输入备注信息"
          :disabled="isViewMode"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { followApi } from "@/api/follow";
import { userKey } from "@/utils/auth";
import { storageLocal } from "@pureadmin/utils";
import dayjs from "dayjs";
import { ElMessage } from "element-plus";
import { computed, defineEmits, defineProps, onMounted, ref, watch } from "vue";

// 定义随访计划任务参数接口（因为API中没有导出）
interface FollowUpTaskParams {
  userId: number; // 被随访用户ID，必需
  plansPeriodId: number; // 计划周期ID，必需
  startDate: string; // 开始时间戳(毫秒)，必需。例如: "1642219200000"
  endDate: string; // 结束时间戳(毫秒)，必需。例如: "1642219200000"
  executionTime: string; // 随访时间，必需。例如: "08:00-09:00"
  notes?: string; // 备注，可选
  planId?: number; // 计划ID，可选
}

const props = defineProps<{
  userId: number;
  planId?: number;
  mode?: "create" | "edit" | "view"; // 组件模式：创建、编辑、查看
}>();

// 默认模式为创建
const defaultMode = computed(() => props.mode || "create");

// 计算是否为查看模式
const isViewMode = computed(() => defaultMode.value === "view");

// 计算是否为编辑模式
const isEditMode = computed(() => defaultMode.value === "edit");

// 计算是否为创建模式
const isCreateMode = computed(() => defaultMode.value === "create");
onMounted(() => {
  getFollowUpPlanCondition();
});
const emit = defineEmits(["update:modelValue", "submit"]);
const getFollowUpPlanCondition = async () => {
  const response = await followApi.getFollowUpPlanCondition({
    userId: (storageLocal().getItem(userKey) as any).userId
  });
  if (response?.data) {
    followUpPlanCondition.value = response.data.plansPeriodList;
  }
};
// 表单引用
const formRef = ref();

// 时间选择器的值
const timeValue = ref<[Date, Date] | null>(null);
const followUpPlanCondition = ref<any[]>([]);
// 表单数据
const formData = ref<FollowUpTaskParams>({
  userId: props.userId,
  plansPeriodId: 1,
  startDate: "",
  endDate: "",
  executionTime: "",
  notes: "",
  planId: props.planId
});

// 表单验证规则
const rules = {
  plansPeriodId: [
    { required: true, message: "请选择随访周期", trigger: "change" }
  ],
  startDate: [{ required: true, message: "请选择开始日期", trigger: "change" }],
  endDate: [{ required: true, message: "请选择结束日期", trigger: "change" }],
  executionTime: [
    { required: true, message: "请选择随访时间", trigger: "change" }
  ]
};

// 处理时间范围变化
const handleTimeChange = (time: [Date, Date] | null) => {
  if (time) {
    const [start, end] = time;
    formData.value.executionTime = `${dayjs(start).format("HH:mm")}-${dayjs(end).format("HH:mm")}`;
  } else {
    formData.value.executionTime = "";
  }
};

// 获取随访计划详情
const getFollowUpInfo = async () => {
  if (!props.planId) return;
  try {
    const response = await followApi.getFollowUpPlanFollowUpInfo({
      planId: props.planId
    });
    if (response?.data) {
      const data = response.data;
      formData.value = {
        ...formData.value,
        ...data,
        startDate: String(data.startDate),
        endDate: String(data.endDate)
      };
      // 设置时间选择器的值
      if (data.executionTime) {
        const [start, end] = data.executionTime.split("-");
        const now = dayjs();
        timeValue.value = [
          now
            .hour(Number(start.split(":")[0]))
            .minute(Number(start.split(":")[1]))
            .toDate(),
          now
            .hour(Number(end.split(":")[0]))
            .minute(Number(end.split(":")[1]))
            .toDate()
        ];
      }
    }
  } catch (error) {
    console.error("获取随访计划详情失败:", error);
    ElMessage.error("获取随访计划详情失败");
  }
};

// 提交表单
const submitForm = async () => {
  console.log("提交随访计划表单 - 开始验证和提交，模式:", defaultMode.value);

  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    let response;
    if (isCreateMode.value) {
      // 创建新的随访计划
      console.log("随访计划 - 创建模式，调用创建接口", formData.value);
      response = await followApi.getFollowUpPlanFollowUpCreate(formData.value);
    } else if (isEditMode.value && props.planId) {
      // 编辑现有随访计划
      console.log("随访计划 - 编辑模式，调用更新接口，计划ID:", props.planId);
      response = await followApi.getFollowUpPlanFollowUpUpdate(formData.value);
    } else {
      console.error("随访计划 - 无效的操作模式或缺少计划ID");
      ElMessage.error("操作失败，请检查参数");
      return;
    }

    if (response?.data) {
      console.log("提交随访计划表单 - 提交成功", response.data);
      ElMessage.success(isCreateMode.value ? "创建成功" : "更新成功");
      emit("submit", formData.value);
    }
  } catch (error) {
    console.error("保存随访计划失败:", error);
    ElMessage.error("保存失败，请检查表单内容");
  }
};

// 暴露方法给父组件
defineExpose({
  submitForm
});

// 监听 planId 变化
watch(
  () => props.planId,
  newVal => {
    if (newVal) {
      getFollowUpInfo();
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.follow-plan {
  padding: 20px 0;

  :deep(.el-form-item__label) {
    font-weight: normal;
    color: #606266;
  }

  :deep(.el-input__wrapper),
  :deep(.el-textarea__inner) {
    box-shadow: none;
    border: 1px solid #dcdfe6;

    &:hover,
    &:focus {
      border-color: #409eff;
    }
  }

  :deep(.el-select) {
    width: 100%;
  }
}
</style>
